//
//  BiNetwork.swift
//  fho
//
//  Created by 郭颢源 on 2021/4/16.
//

import UIKit

/// 重新定义一个协议，实现TargetType协议方法
protocol BaseTargetType: TargetType {
    
}
// MARK: - 在扩展中实现协议方法
extension BaseTargetType{
    public var baseURL: URL{
        return URL(string: "https://zhizhu.56114.com")!
    }
    
    // 对应的不同API path
    var path: String {
        return ""
    }
    
    // 请求类型
    public var method: Moya.Method {
        return .post
    }
    
    // 请求任务事件（这里附带上参数）
    public var task: Task {
        return .requestPlain
    }
    
    // 是否执行Alamofire验证
    public var validate: Bool {
        return false
    }
    
    // 这个就是做单元测试模拟的数据，只会在单元测试文件中有作用
    public var sampleData: Data {
        return "{}".data(using: String.Encoding.utf8)!
    }
    
    // 请求头
    public var headers: [String: String]? {
        return nil
    }
    
    
}

// MARK: - 网络请求插件 加载状态
let networkPlugin = NetworkActivityPlugin { (activityType, targetType) in
    switch activityType{
    
    case .began:
        JSShowMessage.showTip(msg: "加载中...")
        print("显示loading")
    case .ended:
        JSShowMessage.hidenTip()
        print("隐藏loading")
    }
}

// MARK: - 网络请求插件 设置请求超时时间
let requestTimeoutClosure = { (endpoint: Endpoint, done: @escaping (Result<URLRequest, MoyaError>) -> Void) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 20
        done(.success(request))
    } catch {
        done(.failure(MoyaError.requestMapping(endpoint.url)))
        return
    }
}


/// 服务器返回数据模型
struct Response<T: HandyJSON>: HandyJSON {
    var msg: String?
    var data: T?
    var code: Int = 0
}
/// MARK: - 扩展MoyaProvider，实现request 请求直接返回数据模型
extension MoyaProvider{
    
    //    (_ type : HttpType, urlString : String, parameters : [String : Any]? = nil ,finishedCallBack : @escaping succeedCallBack , failedCallBack :@escaping failedCallBack)
    @discardableResult
    func request<T>(
        _ target: Target,
        completion: @escaping (_ result:Response<T>) -> ()) -> Cancellable?
    {
        
        return request(target) { result1 in
            //            let endTime = CFAbsoluteTimeGetCurrent()
            //            debugPrint(" %f 毫秒", endTime*1000)
            switch result1 {
            case let .success(response):
                do {
                    
                    //let jsonDic = try response.filterSuccessfulStatusCodes().mapJSON() as! NSDictionary
                    let jsonDic = try response.mapJSON() as! NSDictionary
                    let model = JSONDeserializer<Response<T>>.deserializeFrom(dict: jsonDic)
                    completion(model!)
                }catch let error {
                    
                    //errorCallback((error as! MoyaError).response!.statusCode)
                    print((error as! MoyaError).response!.statusCode)
                }
            case let .failure(error):
                //failureCallback(error)
                //                print(MoyaError.jsonMapping(error.response!))
                print(type(of: error))
                print(error.errorDescription!)
                
            }  
        }
    }
}

